#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <unistd.h>
int val = 100; //资源
std::mutex mtx;
std::condition_variable cv;

void consumer(int id){

    while (1)
    {
        {
            std::unique_lock<std::mutex> lock(mtx);
            while(val <= 0)
                cv.wait(lock);
            val--;
            
            std::cout<<"消费线程id:"<<id<<"获取一次资源"<<std::endl;
        }
        sleep(1);
    }
    

}
void product(int id){
    while(1){
        {
            std::unique_lock<std::mutex> lock(mtx);
            val+=5;
            std::cout<<"生产者线程id:"<<id<<"生产一次资源"<<std::endl;
            cv.notify_all();
        }
        sleep(1);
    }
}

int main(){
    std::thread consumerthread[10],productthread[10];
    for(int i = 0; i < 10; i++){
        consumerthread[i] = std::thread(consumer,i);
        productthread[i] = std::thread(product,i);
    }

    for(auto& x : consumerthread){
        x.join();
    }

    for(auto& x : productthread){
        x.join();
    }
}
